<!--客户新增弹窗-->
<template>
  <div ref="container">
    <a-modal
      :title="title"
      :width="1200"
      :visible="visible"
      :confirmLoading="confirmLoading"
      :getContainer="() => $refs.container"
      :maskStyle="{'top':'93px','left':'154px'}"
      :wrapClassName="wrapClassNameInfo()"
      :mask="isDesktop()"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
      :cancelText="$t('button.cancel')"
      :okText="$t('button.save')"
      style="top:10%;height: 80%;">
      <template slot="footer">
        <a-button key="back" v-if="isReadOnly" @click="handleCancel">
          {{ $t('button.cancel') }}
        </a-button>
      </template>
      <div class="modal-content-scroll">
      <a-spin :spinning="confirmLoading">
        <a-form :form="form" id="customerModal">
          <a-row class="form-row" :gutter="24">
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.dealerCode')">
                <a-input v-decorator.trim="[ 'dealerCode' ]"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row class="form-row" :gutter="24">
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.name')">
                <a-input :placeholder="$t('placeholder.pleaseInputName')"
                         v-decorator.trim="[ 'supplier', validatorRules.supplier]" />
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.contacts')">
                <a-input :placeholder="$t('placeholder.pleaseEnterContacts')" v-decorator.trim="[ 'contacts' ]" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row class="form-row" :gutter="24">
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.telephone')">
                <a-input :placeholder="$t('placeholder.pleaseInputTelephone')" v-decorator.trim="[ 'telephone' ]" />
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.phoneNum')">
                <a-input :placeholder="$t('placeholder.pleaseInputPhoneNum')" v-decorator.trim="[ 'phoneNum' ]" />
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.email')">
                <a-input :placeholder="$t('placeholder.pleaseInputEmail')" v-decorator.trim="[ 'email' ]" />
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.fax')">
                <a-input :placeholder="$t('placeholder.pleaseInputFax')" v-decorator.trim="[ 'fax' ]" />
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.beginNeedGet')">
                <a-input
                  v-decorator.trim="[ 'beginNeedGet' ]"/>
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.allNeedGet')">
                <a-input v-decorator.trim="[ 'allNeedGet' ]" :readOnly="true" />
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.taxNum')">
                <a-input v-decorator.trim="[ 'taxNum' ]"/>
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.taxRate')">
                <a-input-number style="width:100%" :placeholder="$t('placeholder.pleaseInputTaxRate')"
                                v-decorator.trim="[ 'taxRate' ]" />
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.bankName')">
                <a-input v-decorator.trim="[ 'bankName' ]"/>
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.accountNumber')">
                <a-input
                  v-decorator.trim="[ 'accountNumber' ]"/>
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.address')">
                <a-input :placeholder="$t('placeholder.pleaseInputAddress')" v-decorator.trim="[ 'address' ]" />
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.sort')">
                <a-input :placeholder="$t('placeholder.pleaseInputSort')" v-decorator.trim="[ 'sort' ]" />
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.creditLimit')">
                <a-input v-decorator.trim="[ 'creditLimit' ]"/>
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.billOverdueDay')">
                <a-input
                  v-decorator.trim="[ 'billOverdueDay' ]"/>
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.area')">
                <a-input :placeholder="$t('placeholder.pleaseArea')" v-decorator.trim="[ 'area' ]"/>
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.seName')">
                <a-select :placeholder="$t('placeholder.pleaseSelectSalesMan')"
                          v-model="personList.value"
                          optionFilterProp="children"
                          :allowClear="true">
                  <a-select-option v-for="(item, index) in personList.options" :key="item.value || item.id || index"
                                   :value="item.value || item.id">
                    {{ item.text || item.label || item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.vatNo')">
                <a-input v-decorator.trim="[ 'vatNo' ]"/>
              </a-form-item>
            </a-col>
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.remark')">
                <a-textarea :rows="2" :placeholder="$t('placeholder.pleaseInputRemark')"
                            v-decorator.trim="[ 'description' ]" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row class="form-row" :gutter="24">
            <a-col :span="24/2">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.billAttachment')"
                           data-step="12" :data-title="$t('search.billAttachment')"
                           :data-intro="$t('placeholder.billAttachmentIntro')">
                <j-upload v-model="fileList" bizPath="customer"></j-upload>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
      </div>
    </a-modal>
  </div>
</template>
<script>
import pick from 'lodash.pick'
import {addSupplier, checkSupplier, editSupplier, getPersonByNumType} from '@/api/api'
import {autoJumpNextInput} from '@/utils/util'
import {mixinDevice} from '@/utils/mixin'
import JUpload from '@/components/jeecg/JUpload'
import {BillModalMixin} from '../../bill/mixins/BillModalMixin'

export default {
  name: 'CustomerModal',
  components: {
    JUpload
  },
  mixins: [mixinDevice, BillModalMixin],
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      isReadOnly: false,
      labelCol: {
        xs: {span: 10},
        sm: {span: 6}
      },
      wrapperCol: {
        xs: {span: 14},
        sm: {span: 18}
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      personList: {
        options: [],
        value: undefined
      },
      fileList: [],
      validatorRules: {
        supplier: {
          rules: [
            {required: true, message: '请输入名称!'},
            {min: 2, max: 60, message: '长度在 2 到 60 个字符', trigger: 'blur'},
            {validator: this.validateSupplierName}
          ]
        }
      }
    }
  },
  created() {

  },
  methods: {
    add() {
      this.edit({})
    },
    async edit(record) {
      await this.initSalesmanSelf()
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.personList.value = this.model && this.model.salesMan != null ? String(this.model.salesMan) : undefined
      this.fileList = this.model.fileName
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'dealerCode', 'supplier', 'contacts', 'telephone', 'email',
          'phoneNum', 'fax', 'beginNeedGet', 'allNeedGet', 'taxNum', 'taxRate', 'vatNo', 'area', 'salesMan',
          'bankName', 'accountNumber', 'address', 'sort', 'description', 'billOverdueDay', 'creditLimit'))
        autoJumpNextInput('customerModal')
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)
          if (this.model.beginNeedGet && this.model.beginNeedPay) {
            that.$message.warn('期初应收和期初应付不能同时输入')
            that.confirmLoading = false
            return
          }
          if (this.fileList && this.fileList.length > 0) {
            formData.fileName = this.fileList
          } else {
            formData.fileName = ''
          }
          formData.salesMan = this.personList.value
          formData.type = '客户'
          let obj
          if (!this.model.id) {
            obj = addSupplier(formData)
          } else {
            obj = editSupplier(formData)
          }
          obj.then((res) => {
            if (res.code === 200) {
              that.$emit('ok')
            } else {
              that.$message.warning(res.data.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateSupplierName(rule, value, callback) {
      let params = {
        name: value,
        type: '客户',
        id: this.model.id ? this.model.id : 0
      }
      checkSupplier(params).then((res) => {
        if (res && res.code === 200) {
          if (!res.data.status) {
            callback()
          } else {
            callback(this.$t('message.attributeNameAlreadyExists'))
          }
        } else {
          callback(res.data)
        }
      })
    },
    initSalesmanSelf() {
      // 返回一个Promise，以便在数据加载完成后执行后续操作
      return new Promise((resolve, reject) => {
        getPersonByNumType({type: 1}).then((res) => {
          if (res) {
            if (res) {
              // 统一为{text, value}，且value为字符串，避免回显数值/字符串不一致
              this.personList.options = res.map(item => ({
                text: item.text || item.label || item.name,
                value: String(item.value || item.id)
              }))
              resolve(res)
            }

          } else {
            reject(new Error('Failed to load salesman data'))
          }
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
</script>
<style scoped>
.modal-content-scroll {
  max-height: calc(80vh - 120px); /* 根据需要调整高度 */
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 10px;
}

/* 美化滚动条 */
.modal-content-scroll::-webkit-scrollbar {
  width: 6px;
}

.modal-content-scroll::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.modal-content-scroll::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}

.modal-content-scroll::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>